// service统一出口
import HYRequest from './request'
import projectSetting from '@/settings/projectSetting'
import sysCache from '@/utils/cache'
import { ElNotification, ElMessageBox } from 'element-plus'
import router from '@/router'

const hyRequest = new HYRequest({
  baseURL: process.env.VUE_APP_API_URL,
  timeout: projectSetting.TIMEOUT,
  interceptors: {
    requestInterceptor: (config: any) => {
      // 携带token的拦截
      const token = sysCache.localCache.getCache('token')
      if (token) {
        config.headers[projectSetting.TOKEN_NAME] = projectSetting.TOKEN_PREFIX + token
      }
      return config
    },
    requestInterceptorCatch: (err) => {
      return err
    },
    responseInterceptor: (res) => {
      return res
    },
    responseInterceptorCatch: (err) => {
      switch (err.response.status) {
        case 401:
          ElMessageBox.confirm(
            '当前用户已被登出或无权限访问当前资源，请尝试重新登录后再操作。',
            '无权限访问',
            {
              type: 'error',
              closeOnClickModal: false,
              center: true,
              confirmButtonText: '重新登录'
            }
          )
            .then(() => {
              router.replace({ path: '/login' })
            })
            // eslint-disable-next-line @typescript-eslint/no-empty-function
            .catch(() => {})
          break
        case 404:
          ElNotification.error({
            title: '请求错误',
            message: 'Status:404，正在请求不存在的服务器记录！'
          })
          break
        case 500:
          ElNotification.error({
            title: '请求错误',
            message: err.response.data || 'Status:500，服务器发生错误！'
          })
          break
        default:
          ElNotification.error({
            title: '请求错误',
            message: err.response.data || `Status:${err.response.status}，未知错误！`
          })
          break
      }
      return err
    }
  }
})

export default hyRequest
